import Component from './Component';

class PureComponent extends Component {
  shouldComponentUpdate(nextProps,nextState){
    //浅比较不相等 才更新
    return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);
  }
}

function shallowEqual(obj1,obj2){
  if(obj1 === obj2){ //浅比较 不关心属性变没变
    return true;
  }


  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false;
  }


  //地址不一样 但浅层长得是一样的 也是认为是相等的
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (const key of keys1) {
    if (!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
}

export default PureComponent;
